﻿Shader "UI/SpriteUV"
{
	Properties
	{
		_Color("Main Color", Color) = (1,1,1,1)
		//要播放的UV动画Texture
		_SpriteTex("SpriteTexture (RGB)", 2D) = "white" {}
		//UV动画的行数
		_SpriteRowCount("RowCounts",float) = 4
		//UV动画的列数  
		_SpriteColumnCount("ColumnCounts",float) = 5
		 //播放速度  
		_Speed("AnimationSpeed",Range(0.01,10)) = 4
	}
	SubShader
	{
		Pass
		{
			//不透明物体  
			Tags{ "RenderType" = "Opaque" }
			//CG开始 
			CGPROGRAM

			//引用变量值 
			#pragma vertex vert
			#pragma fragment frag
			#include "UnityCG.cginc"

			fixed4 _Color;
			uniform sampler2D _SpriteTex;
			uniform float _SpriteRowCount;
			uniform float _SpriteColumnCount;
			uniform float _Speed;

			//顶点输出结构体  
			struct VertexOutput
			{
				float4 pos:SV_POSITION;
				float2 uv:TEXCOORD0;
			};

			//appdate_base Unity预定义的输入结构体 包括了很多信息,可以直接用作为顶点着色程序的输入  
			VertexOutput vert(appdata_base input)
			{
				VertexOutput o;
				o.pos = mul(UNITY_MATRIX_MVP,input.vertex);
				o.uv = input.texcoord.xy;
				return o;
			}

			//片元函数
			float4 frag(VertexOutput input):Color
			{
				//根据行数和列数 算出有多少个精灵 
				float totalSpriteCount = _SpriteRowCount * _SpriteColumnCount;
				// UV坐标值范围为0-1，获取单元格宽度  
				float rowAvgPercent = 1 / _SpriteColumnCount;
				float columnAvgPercent = 1 / _SpriteRowCount;
				//求余数  获取当前精灵索引  
				float SpriteIndex = fmod(_Time.y * _Speed,totalSpriteCount);
				//向下取整  
				SpriteIndex = floor(SpriteIndex);
				//获取当前行索引  
				float columnIndex = fmod(SpriteIndex,_SpriteColumnCount);
				//获取当前列索引  
				float rowIndex = SpriteIndex / _SpriteColumnCount;
				rowIndex = _SpriteRowCount - 1 - floor(rowIndex);
				//计算当前索引所在的精灵的UV坐标  
				float2 spriteUV = input.uv;
				spriteUV.x = (spriteUV.x + columnIndex) * rowAvgPercent;
				spriteUV.y = (spriteUV.y + rowIndex) * columnAvgPercent;
				//获取二维文理坐标color 显示到屏幕
				float4 col = tex2D(_SpriteTex, spriteUV);
				return col;
			}
			//CG结束  
			ENDCG
		}
	}
	//备用shader
	FallBack "Diffuse"
}